package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.wisdge.utils.StringUtils
import net.sf.json.JSON
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.util.Base64Utils

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.security.MessageDigest

/**
 *
 * @Title: apiTpTdxRecycle*
 * @Description:泰迪熊回收
 * @remak ：提供给浙江泰迪熊系统回收接口
 * @author: TH*
 * @date 2023-10-10 11:11:00
 *
 */
public  class apiTpTdxRecycle implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiTpTdxRecycle.class);


    /**
     * 编码
     */
    private static final String ENCODING = "UTF-8";


    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
         httpServletResponse.setCharacterEncoding("UTF-8");
         httpServletResponse.setContentType("application/json;charset=UTF-8");
        //初始化返回参数
        JSONObject result =new JSONObject();

          long starttime=System.currentTimeMillis();

        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        //获取接口调用方式及参数
        String GetMethod=httpServletRequest.getMethod();
        log.debug("[GetMethod]:"+GetMethod);

        String inData="";
        if (GetMethod.equals("GET")){
            inData=httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]"+inData);
        }else {
            InputStreamReader reader=new InputStreamReader(httpServletRequest.getInputStream(),"UTF-8");
            BufferedReader iny=new BufferedReader(reader);
            String line;
            while ((line=iny.readLine())!=null){
                inData+=line;
            }
            log.debug("[原始Post请求参数：]"+inData);
        }
        log.debug("[调用请求信息：]"+inData)


        if (KHUtil.isNull(inData)){
            log.error("入参为空-无法完成操作！");
            result.put("code",-2);
            result.put("message","入参为空-无法完成操作！");

            return  result.toString();
        }



        try{

            JSONObject  inJson=JSONObject.fromObject(inData);
            String taskId=GetJV(inJson,"taskId");//任务ID
            JSONArray customers=inJson.getJSONArray("customers");//客户列表
            String timestamp=GetJV(inJson,"timestamp");//时间戳
            String token=GetJV(inJson,"token");//token


           String IsNullMSG=
                   KHUtil.isNullMSG("taskId",taskId)+
                   KHUtil.isNullMSG("timestamp",timestamp)+
                   KHUtil.isNullMSG("token",token);
            if (!KHUtil.isNull(IsNullMSG)){
                log.error("参数为必填项-无法完成操作！");
                result.put("code",-2);
                result.put("message",IsNullMSG+"参数为空-无法完成操作！");
                return  result.toString();
             }else if (customers.size()<=0){
                log.error("customers外呼任务客户<数组>为必填项-无法完成操作！");
                result.put("code",-2);
                result.put("message","customers外呼任务客户<数组>为空-无法完成操作！");
                return  result.toString();
             }



            /**
             * MD5(accessKey+timestamp+orgName)
             * accessKey是双方协商的参数
             */


            String accessKey = KHDBConfig.getParam(eliteBean, "TDKEY", "");//获取accessKey
            String orgName = KHDBConfig.getParam(eliteBean, "TDXQID", "");//orgName	企业id
            String isString=MD5(accessKey.toString()+timestamp.toString()+orgName.toString());//加个密看看
            log.debug("预期加密Token:"+isString);
            //校验通过
            if (token.equals(isString)){
                log.debug("Token校验通过！");
            }else{
                log.error("Token校验不通过！");
                result.put("code",-2);
                result.put("message","Token校验不通过-无法完成操作！");
                return  result.toString();
            }




          for(int i=0;i<customers.size();i++){
              JSONObject custJson=customers.getJSONObject(i);
              String name=GetJV(custJson,"name");//姓名
              String phone=GetJV(custJson,"phone");//手机
              String exendFieds=GetJV(custJson,"extendFields");
              String objective_Guid=null;
              String tagRemark=null;
              String calllTags=null;
              String ordinaryTags=null;
              String aiTags=null;

              tagRemark= GetJV(custJson, "tagRemark");//标签备注
              calllTags= GetJV(custJson, "callTags");//通话标签
              ordinaryTags= GetJV(custJson, "ordinaryTags");//场景流程标签
              aiTags= GetJV(custJson, "aiTags");//场景AI标签
              if (!KHUtil.isNull(exendFieds)) {
                  JSONObject exendFiedsJson = JSONObject.fromObject(exendFieds);
                  objective_Guid= GetJV(exendFiedsJson, "EXTEND1");//任务名单ID

              }
              String IsNullMSG2=
                              KHUtil.isNullMSG("phone",phone)+
                              KHUtil.isNullMSG("extendFields",exendFieds)+
                              KHUtil.isNullMSG("EXTEND1",objective_Guid)+
                              KHUtil.isNullMSG("name",name);
              if (!KHUtil.isNull(IsNullMSG2)) {
                  log.error("参数为必填项-无法完成操作！");
                  result.put("code", -2);
                  result.put("message", IsNullMSG2 + "参数为空-无法完成操作！");
                  return result.toString();
              }


              //查询话单表有没有数据
             String chaxunevent='''select OBJECTIVE_GUID from tdx_bill_list where OBJECTIVE_GUID =? ''';
              List<Map<String, Object>> selectEventExits = jt.queryForList(chaxunevent,objective_Guid);



              if (KHUtil.isNull(calllTags)&&selectEventExits.size()<=0){
                  //插入回收列表
                    String insertSql='''  
                               Insert 
                               into 
                               TDX_RECYCLE_LIST
                               (
                               REC_GUID,
                               OBJECTIVE_GUID,
                               TASKID,
                               CUSTOMERNAME,
                               MOBILE,
                               CREATEDDATE  
                               )VALUES
                               (
                               sysguid,
                               ?,
                               ?,
                               ?,
                               ?,
                               sysdate
                               )
                              ''';
              jt.update(insertSql,objective_Guid,taskId,name,phone);


              //删除泰迪熊推送表数据
              String deleteSql=''' DELETE FROM TDX_PUSH_LIST where OBJECTIVE_GUID=? and TASKID=? ''';
              jt.update(deleteSql,objective_Guid,taskId);

             //修改名单状态
              String updateSql='''  
                               update 
                               OBJECTIVE
                               Set 
                               HANDLEBY_ID=null
                               where OBJECTIVE_GUID=?
                              ''';
              jt.update(updateSql,objective_Guid);
              //修改名单状态
              String updateSql2='''  
                               update 
                               Elitetask
                               Set 
                               HANDLEBY_ID=null
                               where OBJECTIVE_GUID=?
                              ''';
              jt.update(updateSql2,objective_Guid);
          }else{

                  String selectsql='''select OBJECTIVE_GUID FROM TDX_CALL_LOSS where OBJECTIVE_GUID =?''';
                  List<Map<String, Object>> sqllist = jt.queryForList(selectsql,objective_Guid);

                  if (sqllist.size()>0){
                  String updatesql='''
                               Update  TDX_CALL_LOSS 
                               Set 
                               NAME=?,
                               PHONE=?,
                               TAG_REMARK=?,
                               CALL_TAGS=?,
                               ORDINARYTAGS=?,
                               AITAGS=?,
                               TASKID=?,
                               UPDATEDATE=sysdate
                               where OBJECTIVE_GUID=?
                                          ''';

                      jt.update(updatesql,name,phone,tagRemark,calllTags,ordinaryTags,aiTags,taskId,objective_Guid);
                  }else{
                      //插入呼损标签表
                      String insertSql='''  
                               Insert 
                               into 
                               TDX_CALL_LOSS
                               (
                               REC_GUID,
                               NAME,
                               PHONE,
                               OBJECTIVE_GUID,
                               TAG_REMARK,
                               CALL_TAGS,
                               ORDINARYTAGS,
                               AITAGS,
                               CREATEDDATE,
                               taskId
                               )VALUES
                               (
                               sysguid,
                               ?,
                               ?,
                               ?,
                               ?,
                               ?,
                               ?,
                               ?,
                               sysdate,
                               ?
                               )
                              ''';
                      jt.update(insertSql,name,phone,objective_Guid,tagRemark,calllTags,ordinaryTags,aiTags,taskId);
                  }

              }
          }




            long endtime=System.currentTimeMillis();
            result.put("code", 200);
            result.put("message","处理成功！耗时:"+(endtime-starttime)+"毫秒");
            result.put("timestamp",timestamp);


        }catch (Exception e) {
            log.error("接口处理异常", e);
            result.put("code", -1);
            result.put("message","接口处理异常:"+ e.getMessage());

        }





        return result.toString();
    }


    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

    // MD5加码。32位
    public static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];

        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }



}
